package org.kevin.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @ClassName: MySecurity
 * @Description: TODO
 * @Author: kevinHan
 * @Date: 2019/8/25 15:39
 * @Version: 1.0
 */
@EnableWebSecurity
public class MySecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /** 定制请求的授权规则 */
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/grade1/**").hasRole("g1")
                                .antMatchers("/grade2/**").hasRole("g2")
                                .antMatchers("/grade3/**").hasRole("g3");

        /** 开启自动配置的登陆功能
         * 如果没有登陆，没有权限会来到登陆页面
         * */
        http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin");

        /** 开启自动配置的注销功能 */
        //注销成功，回到首页，访问/logout表示注销，清空session，注销成功后会返回/login?logout页面
        http.logout().logoutSuccessUrl("/");

        /** 开启记住我 */
        //登陆成功后，将cookie发给浏览器保存，以后访问页面带上cookie，只要通过检查就可以免登陆了
        //点击注销会删除cookie
        http.rememberMe().rememberMeParameter("remember");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("康康").password(new BCryptPasswordEncoder().encode("1")).roles("g1","g2")
                                    .and().passwordEncoder(new BCryptPasswordEncoder()).withUser("小红").password(new BCryptPasswordEncoder().encode("1")).roles("g2","g3")
                                    .and().passwordEncoder(new BCryptPasswordEncoder()).withUser("kevin").password(new BCryptPasswordEncoder().encode("1")).roles("g1","g2","g3");
    }
}
